package com.rzjm.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import rk.netDevice.sdk.p2.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Service
public class CGQRSServer {

    @Value("${rsserver.port}")
    private int port;

    @Resource
    private DeviceService deviceService;
    @Resource
    private TerminalTemperatureService temperatureService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private UserService userService;
    @Resource
    private ShopService shopService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserMpService userMpService;
    @Resource
    private DeviceNodeService deviceNodeService;
    @Resource
    private DevicePowerRecordService devicePowerRecordService;
    @Resource
    private DevicePowerConsumptionService powerConsumptionService;
    @Resource
    private FeedService feedService;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Value("${web.appid_mp}")
    private String appidMp;//公众号appid
    @Value("${web.secret_mp}")
    private String secretMp;//公众号secret

    /**
     *  启动监听服务
     * @throws InterruptedException
     */
    public void start() throws InterruptedException{
        RSServer rsServer = RSServer.Initiate(port);// 初始化
        System.out.println("传感器监听 端口： " + port + "  启动成功，等待监听...");
        rsServer.addDataListener(new IDataListener() {// 添加监听

            @Override
            public void receiveTimmingAck(TimmingAck data) {// 校时指令应答处理
                System.out.println("校时应答->设备编号:" + data.getDeviceId()
                        + "\t执行结果：" + data.getStatus());
            }

            @Override
            public void receiveTelecontrolAck(TelecontrolAck data) {// 遥控指令应答处理
                System.out.println("遥控应答->设备编号:" + data.getDeviceId()
                        + "\t继电器编号:" + data.getRelayId() + "\t执行结果:" + data.getStatus());
            }

            @Override
            public void receiveStoreData(StoreData data) {// 已存储数据接收处理
                // 遍历节点数据。数据包括网络设备的数据以及各个节点数据。温湿度数据存放在节点数据中
                for (NodeData nd : data.getNodeList()) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
                    String str = sdf.format(nd.getRecordTime());
                    System.out.println("存储数据->设备地址:" + data.getDeviceId()
                            + "\t节点:" + nd.getNodeId() + "\t温度:" + nd.getTem()
                            + "\t湿度:" + nd.getHum() + "\t存储时间:" + str);
                }
            }

            @Override
            public void receiveRealtimeData(RealTimeData data) {// 实时数据接收处理
//                System.out.println("测温电流设备信息：" + data.toString());

                // 遍历节点数据。数据包括网络设备的数据以及各个节点数据。温湿度数据存放在节点数据中
                for (NodeData nd : data.getNodeList()) {
//
                    String dataStr = "实时数据->设备地址:" + data.getDeviceId()
                            + "\t节点:" + nd.getNodeId() + "\t温度:" + nd.getTem()
                            + "\t湿度:" + nd.getHum() + "\t经度:" + data.getLng()
                            + "\t纬度:" + data.getLat() + "\t坐标类型:"
                            + data.getCoordinateType() + "\t继电器状态:"
                            + data.getRelayStatus();
//                    System.out.println(dataStr);

                    try {
                        int deviceType = 0;
                        int terminal_num = data.getDeviceId();
                        QueryWrapper<Device> qw = new QueryWrapper<>();
                        qw.eq("device_num", String.valueOf(terminal_num));
                        qw.last("limit 1");
                        Device device = deviceService.getOne(qw);
                        if (device != null) {

                            Shop shop = shopService.findById(device.getShopId());
                            if(shop.getState() == 0){
                                System.out.println(shop.getShopName() + " 企业已被禁用");
                                return;
                            }

                            if(device.getIsShowLog() == 1){
                                System.out.println(dataStr);
                            }

                            int isAddRecord = 0;
                            deviceType = device.getDeviceType();
                            double ins0 = nd.getHum();
                            double ins1 = nd.getTem();

                            //改设备类型 数值需要计算
                            //ins 0
                            double voltage = 0.00d;
                            //ins 1
                            double electric = 0.00d;

                            QueryWrapper<DeviceNode> qwNode = new QueryWrapper<>();
                            qwNode.eq("device_id",device.getId());
                            qwNode.eq("node_index",nd.getNodeId());
                            List<DeviceNode> nodes = deviceNodeService.list(qwNode);
                            if(CollUtil.isNotEmpty(nodes)){
                                for (DeviceNode deviceNode0 : nodes){

                                    //改设备类型 数值需要计算
                                    //ins 0
                                    double temp0 = 0.00d;
                                    //ins 1
                                    double temp1 = 0.00d;

                                    //记录上报频率
                                    int intervalSecond = deviceNode0.getIntervalSecond();

                                    Date lastActiveTime = deviceNode0.getLastActiveTime();
                                    if(lastActiveTime != null){
                                        Date valideTime = DateUtil.getAfterSecondsByOld(lastActiveTime, intervalSecond);
                                        //如果当前时间 已经 在频率时间之后  60秒之后  才记录数据
                                        if (new Date().getTime() > valideTime.getTime()) {
                                            isAddRecord = 1;
                                        }
                                    }else{
                                        isAddRecord = 1;
                                    }

                                    double addValue = 0.00d;
                                    if (deviceNode0.getAddValue() != null) {
                                        addValue = deviceNode0.getAddValue();
                                    }
                                    if (nd.getHum() == 0 && nd.getTem() == 0) {
                                        System.out.println(data.getDeviceId() + " = 当前节点无数据");
                                        continue;
                                    }

                                    //ins 0
                                    if(deviceNode0.getInsIndex() == 0){//湿度
                                        if (nd.getHum() <= 0) {
                                            System.out.println(data.getDeviceId() + " = 当前节点无数据");
                                            continue;
                                        }
                                        //ins 0
                                        if(deviceNode0.getXishuA()!= null && deviceNode0.getXishuB()!= null){
                                            temp0 = (nd.getHum() * 10 * deviceNode0.getXishuA().doubleValue()) + deviceNode0.getXishuB().doubleValue();
                                            deviceNode0.setCurrentValue((temp0 + (float) addValue));
                                        }
                                    }else{//温度
                                        if (nd.getTem() <= 0) {
                                            System.out.println(data.getDeviceId() + " = 当前节点无数据");
                                            continue;
                                        }
                                        //ins 0
                                        if(deviceNode0.getXishuA()!= null && deviceNode0.getXishuB()!= null) {
                                            temp1 = (nd.getTem() * 10 * deviceNode0.getXishuA().doubleValue()) + deviceNode0.getXishuB().doubleValue();
                                            deviceNode0.setCurrentValue((temp1 + (float) addValue));
                                        }
                                    }


                                    if (isAddRecord == 1) {
                                        System.out.println("实时数据->设备地址:" + data.getDeviceId()
                                                + "\t节点:" + nd.getNodeId() + "\t温度:" + nd.getTem()
                                                + "\t湿度:" + nd.getHum() + "\t经度:" + data.getLng()
                                                + "\t纬度:" + data.getLat() + "\t坐标类型:"
                                                + data.getCoordinateType() + "\t继电器状态:"
                                                + data.getRelayStatus());
                                        double warnMaxValue = device.getWarnMaxValue();
                                        double warnMinValue = device.getWarnMinValue();
                                        boolean isFeedValue = false; // 是否是绑定了饲料的设备预警
                                        boolean isIgnor = false; // 绑定了饲料的设备预警,换饲料期间数据设为true
                                        double[] warnMaxValueArr = null;
                                        double[] warnMinValueArr = null;
                                        deviceNode0.setLastActiveTime(new Date());
                                        //设备类型  2 - 测温度 3 - 测电流  4 - 测重量
                                        // 2 - 测温度
                                        System.out.println("设备预警devicenodeid:"+deviceNode0.getId());
                                        if (deviceNode0.getDeviceType() == 2) {
                                            System.out.println("设备预警:"+deviceNode0.getTerminalName());
                                            if (deviceNode0.getFeedId() != null){
                                                Feed feed = feedService.findById(deviceNode0.getFeedId());
                                                if (feed != null){
                                                    isFeedValue = true;
                                                }
                                                if (feed != null && feed.getHighTemperature() != null && feed.getUnqualifiedIntervalValue() != null){ // 饲料预警在温度范围内的才预警
//                                                    warnMaxValue = feed.getHighTemperature();
                                                    warnMaxValueArr = new double[]{feed.getHighTemperature(),
                                                            feed.getHighTemperature() + feed.getUnqualifiedIntervalValue()};
//                                                    System.out.println("设备预警:"+deviceNode0.getTerminalName()+"warnMaxValue["+warnMaxValueArr[0]+","
//                                                            + warnMaxValueArr[1] + "]");
                                                }
                                                if (feed != null && feed.getLowTemperature() != null){
//                                                    warnMinValue = feed.getLowTemperature();
                                                    warnMinValueArr = new double[]{feed.getLowTemperature() - feed.getUnqualifiedIntervalValue(),
                                                            feed.getLowTemperature()};
//                                                    System.out.println("设备预警:"+deviceNode0.getTerminalName()+"warnMinValue["+warnMinValueArr[0]+","
//                                                            + warnMinValueArr[1] + "]");
                                                }
                                            }
                                            temp0 = (nd.getHum() * 10 * deviceNode0.getXishuA().doubleValue()) + deviceNode0.getXishuB().doubleValue();

                                            temp1 = (nd.getTem() * 10 * deviceNode0.getXishuA().doubleValue()) + deviceNode0.getXishuB().doubleValue();

                                            deviceNode0.setCurrentValue((temp0 + (float) addValue));
                                            deviceNodeService.updateById(deviceNode0);

//                                            TerminalTemperature temperature0 = new TerminalTemperature();
//                                            temperature0.setShopId(device.getShopId());
//                                            temperature0.setCreateTime(new Date());
//                                            temperature0.setDeviceId(device.getId());
//                                            temperature0.setWendu((float) (temp0) + (float) addValue);
//                                            temperature0.setNodeIndex(nd.getNodeId());
//                                            temperature0.setInsIndex(0);
//                                            temperatureService.save(temperature0);

                                            TerminalTemperature temperature1 = null;
                                            if (nd.getTem() > 0) {
                                                QueryWrapper<DeviceNode> qwNode1 = new QueryWrapper<>();
                                                qwNode1.eq("device_id", device.getId());
                                                qwNode1.eq("node_index", nd.getNodeId());
                                                qwNode1.eq("ins_index", 1);
                                                qwNode1.last("limit 1");
                                                DeviceNode deviceNode1 = deviceNodeService.getOne(qwNode1);
                                                if (deviceNode1 != null) {

                                                    if((float) temp1 > 0){
                                                        temperature1 = new TerminalTemperature();
                                                        if (deviceNode1.getFeedId() != null){
                                                            Feed feed = feedService.findById(deviceNode1.getFeedId());
                                                            if (feed != null){
                                                                temperature1.setHighTemperature(feed.getHighTemperature());
                                                                temperature1.setLowTemperature(feed.getLowTemperature());
                                                                temperature1.setUnqualifiedIntervalValue(feed.getUnqualifiedIntervalValue());
                                                            }
                                                        }
                                                        if(deviceNode1.getIgnorTime() != null && (deviceNode1.getIgnorTime().compareTo(new Date()) > 0)){
                                                            temperature1.setIsIgnor(1);
                                                            isIgnor = true;
                                                        }
                                                        temperature1.setShopId(device.getShopId());
                                                        temperature1.setCreateTime(new Date());
                                                        temperature1.setDeviceId(device.getId());
                                                        temperature1.setWendu((float) temp1 + (float) addValue);
                                                        System.out.println("1  nd.getNodeId() = " + nd.getNodeId());
                                                        temperature1.setNodeIndex(nd.getNodeId());
                                                        temperature1.setInsIndex(1);
                                                        temperature1.setInsIndex(1);
                                                        temperature1.setFeedId(deviceNode1.getFeedId());
                                                        temperature1.setFeedName(deviceNode1.getFeedName());
                                                        temperatureService.save(temperature1);
                                                        deviceNode1.setCurrentValue(temp1 + (float) addValue);
                                                        deviceNodeService.updateById(deviceNode1);
                                                    }
                                                }
                                            }

                                        }
                                        // 3 - 测电流
                                        else if (deviceNode0.getDeviceType() == 3) {
                                            electric = temp0;

                                            if (temp0 > 2) {
                                                System.out.println(data.getDeviceId() + " = 当前电流：" + deviceNode0.getPowerState());
                                                //当前  关机 ->  开机
                                                if (deviceNode0.getPowerState() == 0) {
                                                    deviceNode0.setPowerState(1);
                                                    Date openTime = new Date();
                                                    deviceNode0.setPowerOpenTime(openTime);
                                                    deviceNode0.setPowerOffTime(null);

                                                    DevicePowerRecord powerRecord = new DevicePowerRecord();
                                                    powerRecord.setCreateTime(new Date());
                                                    powerRecord.setNodeId(deviceNode0.getId());
                                                    powerRecord.setNodeName(deviceNode0.getTerminalName());
                                                    powerRecord.setDeviceId(deviceNode0.getDeviceId());
                                                    powerRecord.setPowerOpenTime(openTime);
                                                    powerRecord.setPowerState(1);
                                                    devicePowerRecordService.save(powerRecord);


                                                    deviceNode0.setPowerRecordId(powerRecord.getId());
                                                }
                                            } else {
                                                //当前  开机 ->  关机
                                                if (deviceNode0.getPowerState() == 1) {
                                                    deviceNode0.setPowerState(0);

                                                    Date closeTime = new Date();
                                                    deviceNode0.setPowerOffTime(closeTime);

                                                    if (deviceNode0.getPowerRecordId() != null && deviceNode0.getPowerRecordId() > 0) {
                                                        DevicePowerRecord powerRecord = devicePowerRecordService.findById(deviceNode0.getPowerRecordId());
                                                        if (powerRecord != null) {
                                                            powerRecord.setPowerOffTime(closeTime);
                                                            devicePowerRecordService.updateById(powerRecord);
                                                        }
                                                    }
                                                }
                                            }
                                            deviceNode0.setCurrentValue((temp0 + (float) addValue));
                                            deviceNodeService.updateById(deviceNode0);
                                        }
                                        // 4 - 测重量
                                        else if (deviceNode0.getDeviceType() == 4) {
                                            System.out.println(" ========= 测试重量请求数据：" + dataStr);

                                            if(nd.getHum() != 0 && nd.getTem() != 0){

                                                String left = String.valueOf(nd.getHum());
                                                String right = String.valueOf(nd.getTem());
                                                float value = ByteUtil.heBingLeftAndRight(left,right);

                                                temp0 = value;
                                                System.out.println("测重量设备：" + value + " KG");

                                                deviceNode0.setCurrentValue(Double.parseDouble(value+""));
                                                deviceNodeService.updateById(deviceNode0);
                                            }


//                                            if(deviceNode0.getInsIndex() == 0){//湿度
//                                                if (nd.getHum() <= 0) {
//                                                    System.out.println(data.getDeviceId() + " = 当前节点无数据");
//                                                    continue;
//                                                }
//                                                //ins 0
//                                                temp0 = (nd.getHum() * 10 * deviceNode0.getXishuA().doubleValue()) + deviceNode0.getXishuB().doubleValue();
//                                                deviceNode0.setCurrentValue((temp0 + (float) addValue));
//                                                System.out.println(data.getDeviceId() + " = 当前电压：" + temp0);
//                                            }else{//温度
//                                                if (nd.getTem() <= 0) {
//                                                    System.out.println(data.getDeviceId() + " = 当前节点无数据");
//                                                    continue;
//                                                }
//                                                //ins 0
//                                                temp1 = (nd.getTem() * 10 * deviceNode0.getXishuA().doubleValue()) + deviceNode0.getXishuB().doubleValue();
//                                                deviceNode0.setCurrentValue((temp1 + (float) addValue));
//                                                System.out.println(data.getDeviceId() + " = 当前电压：" + temp1);
//                                            }
//
//                                            voltage = temp1;
//                                            deviceNodeService.updateById(deviceNode0);
                                        }
                                        // 6 - 测电压设备
                                        else if (deviceNode0.getDeviceType() == 6) {
                                            if(deviceNode0.getInsIndex() == 0){//湿度
                                                if (nd.getHum() <= 0) {
                                                    System.out.println(data.getDeviceId() + " = 当前节点无数据");
                                                    continue;
                                                }
                                                //ins 0
                                                if(deviceNode0.getXishuA()!= null && deviceNode0.getXishuB()!= null) {
                                                    temp0 = (nd.getHum() * 10 * deviceNode0.getXishuA().doubleValue()) + deviceNode0.getXishuB().doubleValue();
                                                    deviceNode0.setCurrentValue((temp0 + (float) addValue));
                                                }
                                                System.out.println(data.getDeviceId() + " = 当前电压：" + temp0);
                                            }else{//温度
                                                if (nd.getTem() <= 0) {
                                                    System.out.println(data.getDeviceId() + " = 当前节点无数据");
                                                    continue;
                                                }
                                                //ins 0
                                                if(deviceNode0.getXishuA()!= null && deviceNode0.getXishuB()!= null) {
                                                    temp1 = (nd.getTem() * 10 * deviceNode0.getXishuA().doubleValue()) + deviceNode0.getXishuB().doubleValue();
                                                    deviceNode0.setCurrentValue((temp1 + (float) addValue));
                                                }
                                                System.out.println(data.getDeviceId() + " = 当前电压：" + temp1);
                                            }

                                            voltage = temp1;
                                            deviceNodeService.updateById(deviceNode0);
                                        }


                                        // 3种类型  共用
                                        TerminalTemperature temperature0 = null;
                                        if((float) (temp0) > 0){
                                            temperature0 = new TerminalTemperature();
                                            temperature0.setShopId(device.getShopId());
                                            temperature0.setCreateTime(new Date());
                                            temperature0.setDeviceId(device.getId());
                                            temperature0.setWendu((float) (temp0) + (float) addValue);
                                            temperature0.setNodeIndex(nd.getNodeId());
                                            temperature0.setInsIndex(deviceNode0.getInsIndex());
                                            temperature0.setFeedId(deviceNode0.getFeedId());
                                            temperature0.setFeedName(deviceNode0.getFeedName());
                                            if (deviceNode0.getFeedId() != null){
                                                Feed feed = feedService.findById(deviceNode0.getFeedId());
                                                if (feed != null){
                                                    temperature0.setHighTemperature(feed.getHighTemperature());
                                                    temperature0.setLowTemperature(feed.getLowTemperature());
                                                    temperature0.setUnqualifiedIntervalValue(feed.getUnqualifiedIntervalValue());
                                                }
                                            }
                                            if(deviceNode0.getIgnorTime() != null && (deviceNode0.getIgnorTime().compareTo(new Date()) > 0)){
                                                temperature0.setIsIgnor(1);
                                                isIgnor = true;
                                            }
                                            temperatureService.save(temperature0);
                                        }



//                                        Date lastWarnTime = device.getLastWarnTime();
                                        Date lastWarnTime = deviceNode0.getLastWarnTime();

                                        Calendar calendar = Calendar.getInstance();
                                        if (lastWarnTime == null) {
                                            calendar.setTime(new Date());
                                        } else {
                                            calendar.setTime(lastWarnTime);
                                        }

                                        calendar.add(Calendar.MINUTE, device.getWarningTimeInterval());

                                        long lastTimespan = calendar.getTime().getTime();
                                        long nowTimespan = new Date().getTime();


                                        if (isFeedValue && isInrange(warnMaxValueArr, (float) (temp0) + (float) addValue)){
                                            if (temperature0 != null){
                                                temperature0.setIsUnqualified(1);
                                                temperatureService.updateById(temperature0);
                                            }
                                            if (!isIgnor && device.getIsStartMaxWarning() == 1 && nowTimespan > lastTimespan) {
//                                                System.out.println("发送超过最高值报警推送消息4: 111111111111111111111111");
                                                //发送报警推送消息
                                                sendWxMsg(device, temperature0, 1, deviceNode0);
                                                device.setLastWarnTime(new Date());
                                                UpdateWrapper<DeviceNode> deviceNodeUpdateWrapper = new UpdateWrapper<>();
                                                deviceNodeUpdateWrapper.eq("id", deviceNode0.getId());
                                                deviceNodeUpdateWrapper.set("last_warn_time", new Date());
                                                deviceNodeService.update(deviceNodeUpdateWrapper);
                                            }
                                        }else if (isFeedValue && isInrange(warnMinValueArr, (float) (temp0) + (float) addValue)){
                                            if (temperature0 != null){
                                                temperature0.setIsUnqualified(1);
                                                temperatureService.updateById(temperature0);
                                            }
                                            if (!isIgnor && device.getIsStartMinWarning() == 1 && nowTimespan > lastTimespan) {
//                                            System.out.println("发送低于最低值的报警推送消息3: 2222222222222222222222222");
                                                //发送报警推送消息
                                                sendWxMsg(device, temperature0, 2, deviceNode0);
                                                device.setLastWarnTime(new Date());
                                                UpdateWrapper<DeviceNode> deviceNodeUpdateWrapper = new UpdateWrapper<>();
                                                deviceNodeUpdateWrapper.eq("id", deviceNode0.getId());
                                                deviceNodeUpdateWrapper.set("last_warn_time", new Date());
                                                deviceNodeService.update(deviceNodeUpdateWrapper);
                                            }
                                        }else if (!isFeedValue && warnMaxValue <= (float) (temp0) + (float) addValue) {//当前值超过  最大值报警
//                                        System.out.println("开始报警: " + temp0);
                                            if (device.getIsStartMaxWarning() == 1 && nowTimespan > lastTimespan) {
//                                        System.out.println("发送超过最高值报警推送消息4: 33333333333333333333333");
                                                //发送报警推送消息
                                                sendWxMsg(device, temperature0, 1, deviceNode0);
                                                device.setLastWarnTime(new Date());
                                                UpdateWrapper<DeviceNode> deviceNodeUpdateWrapper = new UpdateWrapper<>();
                                                deviceNodeUpdateWrapper.eq("id", deviceNode0.getId());
                                                deviceNodeUpdateWrapper.set("last_warn_time", new Date());
                                                deviceNodeService.update(deviceNodeUpdateWrapper);
                                            }
                                        } else if (!isFeedValue && warnMinValue >= (float) (temp0) + (float) addValue) {//当前值低于 最小值报警
//                                        System.out.println("开始报警: " + temp0);
                                            if (device.getIsStartMinWarning() == 1 && nowTimespan > lastTimespan) {
//                                        System.out.println("发送低于最低值的报警推送消息3: 4444444444444444444444");
                                                //发送报警推送消息
                                                sendWxMsg(device, temperature0, 2, deviceNode0);
                                                device.setLastWarnTime(new Date());
                                                UpdateWrapper<DeviceNode> deviceNodeUpdateWrapper = new UpdateWrapper<>();
                                                deviceNodeUpdateWrapper.eq("id", deviceNode0.getId());
                                                deviceNodeUpdateWrapper.set("last_warn_time", new Date());
                                                deviceNodeService.update(deviceNodeUpdateWrapper);
                                            }
                                        }
                                        System.out.println("设备预警:========nd.getTem()"+ nd.getTem() + ">>>>>>======" + (warnMinValue >= temp0 ? "true": "false" ));
                                        if (nd.getTem() > 0 && temperature0 != null) {
                                            if (isFeedValue && isInrange(warnMaxValueArr, (float) (temp0) + (float) addValue)){
                                                if (temperature0 != null){
                                                    temperature0.setIsUnqualified(1);
                                                    temperatureService.updateById(temperature0);
                                                }
                                                if (!isIgnor && device.getIsStartMaxWarning() == 1 && nowTimespan > lastTimespan) {
//                                        System.out.println("发送超过最高值报警推送消息:5555555555555555555555 " );
                                                    //发送报警推送消息
                                                    sendWxMsg(device, temperature0, 1, deviceNode0);
                                                    device.setLastWarnTime(new Date());
                                                    UpdateWrapper<DeviceNode> deviceNodeUpdateWrapper = new UpdateWrapper<>();
                                                    deviceNodeUpdateWrapper.eq("id", deviceNode0.getId());
                                                    deviceNodeUpdateWrapper.set("last_warn_time", new Date());
                                                    deviceNodeService.update(deviceNodeUpdateWrapper);
                                                }
                                            }else if (isFeedValue && isInrange(warnMinValueArr, (float) (temp0) + (float) addValue)){
                                                if (temperature0 != null){
                                                    temperature0.setIsUnqualified(1);
                                                    temperatureService.updateById(temperature0);
                                                }
                                                if (!isIgnor && device.getIsStartMinWarning() == 1 && nowTimespan > lastTimespan) {
//                                        System.out.println("发送低于最低值的报警推送消息2:666666666666666666666666 " );
                                                    //发送报警推送消息
                                                    sendWxMsg(device, temperature0, 2, deviceNode0);
                                                    device.setLastWarnTime(new Date());
                                                    UpdateWrapper<DeviceNode> deviceNodeUpdateWrapper = new UpdateWrapper<>();
                                                    deviceNodeUpdateWrapper.eq("id", deviceNode0.getId());
                                                    deviceNodeUpdateWrapper.set("last_warn_time", new Date());
                                                    deviceNodeService.update(deviceNodeUpdateWrapper);
                                                }
                                            }else if (!isFeedValue && warnMaxValue <= (float) (temp0) + (float) addValue) {//当前值超过  最大值报警
//                                            System.out.println("开始报警: " + temp0);
                                                if (device.getIsStartMaxWarning() == 1 && nowTimespan > lastTimespan) {
//                                        System.out.println("发送超过最高值报警推送消息:77777777777777777777777 " );
                                                    //发送报警推送消息
                                                    sendWxMsg(device, temperature0, 1, deviceNode0);
                                                    device.setLastWarnTime(new Date());
                                                    UpdateWrapper<DeviceNode> deviceNodeUpdateWrapper = new UpdateWrapper<>();
                                                    deviceNodeUpdateWrapper.eq("id", deviceNode0.getId());
                                                    deviceNodeUpdateWrapper.set("last_warn_time", new Date());
                                                    deviceNodeService.update(deviceNodeUpdateWrapper);
                                                }
                                            } else if (!isFeedValue && warnMinValue >= (float) (temp0) + (float) addValue) {//当前值低于 最小值报警
//                                            System.out.println("开始报警2: " + temp0);
                                                if (device.getIsStartMinWarning() == 1 && nowTimespan > lastTimespan) {
//                                        System.out.println("发送低于最低值的报警推送消息2: 88888888888888888888888888" );
                                                    //发送报警推送消息
                                                    sendWxMsg(device, temperature0, 2, deviceNode0);
                                                    device.setLastWarnTime(new Date());
                                                    UpdateWrapper<DeviceNode> deviceNodeUpdateWrapper = new UpdateWrapper<>();
                                                    deviceNodeUpdateWrapper.eq("id", deviceNode0.getId());
                                                    deviceNodeUpdateWrapper.set("last_warn_time", new Date());
                                                    deviceNodeService.update(deviceNodeUpdateWrapper);
                                                }
                                            }
                                        }
                                    }
                                }

                                //带 电压 电流的  设备  需要计算 当前使用功率
                                if(device.getDeviceType() == 4){
                                    if(electric > 0 && voltage > 0){
                                        DevicePowerConsumption consumption = new DevicePowerConsumption();
                                        consumption.setDeviceNum(device.getDeviceNum());
                                        consumption.setCreateTime(new Date());
                                        consumption.setDeviceId(device.getId());
                                        consumption.setCreateTime(new Date());
                                        consumption.setVoltage(voltage);
                                        consumption.setElectric(electric);
                                        consumption.setPower(MathUtil.getDoubleUpThree(electric * voltage));
                                        double everyMin =  1.00 / 60.00 / 1000 *  (electric * voltage);
                                        consumption.setCapacity(MathUtil.getDoubleUpThree(everyMin));
                                        consumption.setDataStr(dataStr);
                                        powerConsumptionService.save(consumption);
                                    }
                                }
                            }

                            device.setOnlineState(1);
                            device.setLastActiveTime(new Date());
                            deviceService.updateById(device);

                        } else {
                            System.out.println("登录->设备地址:" + data.getDeviceId() + "不存在");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void receiveLoginData(LoginData data) {// 登录数据接收处理
                System.out.println("登录->设备地址:" + data.getDeviceId());
            }

            @Override
            public void receiveParamIds(ParamIdsData data) {
                String str = "设备参数编号列表->设备编号：" + data.getDeviceId()
                        + "\t参数总数量：" + data.getTotalCount() + "\t本帧参数数量：" + data.getCount() + "\r\n";
                for (int paramId : data.getPararmIdList())// 遍历设备中参数id编号
                {
                    str += paramId + ",";
                }
//                System.out.println(str);
            }

            @Override
            public void receiveParam(ParamData data) {
                String str = "设备参数->设备编号：" + data.getDeviceId() + "\r\n";
                for (ParamItem pararm : data.getParameterList()) {
                    str += "参数编号："
                            + pararm.getParamId()
                            + "\t参数描述："
                            + pararm.getDescription()
                            + "\t参数值："
                            + (pararm.getValueDescription() == null ? pararm
                            .getValue() : pararm.getValueDescription()
                            .get(pararm.getValue())) + "\r\n";
                }
//                System.out.println(str);
            }

            @Override
            public void receiveWriteParamAck(WriteParamAck data) {
                String str = "下载设备参数->设备编号：" + data.getDeviceId() + "\t参数数量："
                        + data.getCount() + "\t"
                        + (data.isSuccess() ? "下载成功" : "下载失败");
                System.out.println(str);
            }

            @Override
            public void receiveTransDataAck(TransDataAck data) {
                String str = "数据透传->设备编号：" + data.getDeviceId() + "\t响应结果："
                        + data.getData() + "\r\n字节数：" + data.getTransDataLen();
                System.out.println(str);
            }

            @Override
            public void receiveHeartbeatData(HeartbeatData heartbeatData) {

            }
        });
        rsServer.start();
    }

    /**
     *
     * @param device
     * @param temperature
     * @param warnType  1 - 超过最大值  2 - 低于最小值
     */
    private void sendWxMsg(Device device, TerminalTemperature temperature,Integer warnType, DeviceNode node){
        try{
            if(temperature != null){
                String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp, 1);
                QueryWrapper<SysUser> qw = new QueryWrapper<>();
                qw.eq("shop_id",device.getShopId())
                        .and(wrapper -> wrapper.eq("user_type", 4).or().eq("user_type", 6));
                List<SysUser> sysUsers = sysUserService.list(qw);
                System.out.println("微信公众号推送人sysUsers： "+String.valueOf(sysUsers.size()));
                if(sysUsers != null && sysUsers.size() > 0){
                    String ok_ids = "",error_ids = "";
                    for(SysUser sysUser : sysUsers){
                        List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                        System.out.println("微信公众号推送人users： "+String.valueOf(users.size()));
                        if(users != null){
                            for (User user :users){
                                System.out.println("微信公众号推送人user： ");
                                if(user != null && sysUser.getIsSendMsg() == 1 && StrUtil.isNotEmpty(user.getUnionId())){
                                    System.out.println("微信公众号推送人user： "+ user.getPhonenum()+"unionID:"+user.getUnionId());
                                    WxMsgTemplate template = getTemplate(device,user,temperature,warnType, node);
//                                System.out.println("模板消息：" + template.toString());
                                    String param = JSONUtil.parseObj(template).toString();
                                    JSONObject jsonObject = WxMessage.sendMsg(accessToken,param);
                                    System.out.println("微信公众号推送数据响应： "+jsonObject.toString());
                                    if(jsonObject != null){
                                        int errcode = jsonObject.getInt("errcode");
                                        if(errcode == 0) {//发送成功
                                            ok_ids += user.getId()+",";
                                        }else{//发送失败
                                            error_ids += user.getId()+",";
                                        }
                                        System.out.println("jsonObject:" + jsonObject.toString());
                                    }
                                }
                            }
                        }
                    }

                    ok_ids = StringUtil.getSplitStr(ok_ids);
                    error_ids = StringUtil.getSplitStr(error_ids);
                    temperature.setSendMsgOkIds(ok_ids);
                    temperature.setSendMsgErrorIds(error_ids);
                    temperatureService.updateById(temperature);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }

    /**
     *  温度报警
     * @param device
     * @param user
     * @param temperature
     * @return
     */
    private WxMsgTemplate getTemplate(Device device,User user,TerminalTemperature temperature,Integer warnType,DeviceNode node){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",9);
        QueryWrapper<UserMp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("unionid",user.getUnionId());
        queryWrapper.eq("mp_type","cy");
        UserMp userMp = userMpService.getOne(queryWrapper);
        System.out.println("微信公众号推送人userMp： ");
        if(userMp!=null){
            System.out.println("微信公众号推送人userMp： " + userMp.getOpenid());
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();

            //报警项目
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有设备出现温度警报");
            m.put("first",first);

            //报警时间:2018年12月17日 13时20分05秒
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(DateUtil.getTime(temperature.getCreateTime()));
            m.put("keyword1",keyword1);

            //地点:广州五山中公教育大厦1505房
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(device.getAddress());
            m.put("keyword2",keyword2);

            //设备:烟感设备
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(node.getTerminalName() + "(设备SN："+device.getDeviceNum()+")");
            m.put("keyword3",keyword3);

            //报警内容:通道温度报警71.3℃
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getSpicalFontColor());
            keyword4.setValue("当前温度: "+temperature.getWendu() + "℃");
            m.put("keyword4",keyword4);

            //项目负责人:13500008624
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getSpicalFontColor());
            keyword5.setValue(device.getLeaderName() + "("+device.getLeaderPhone()+")");
            m.put("keyword5",keyword5);

            //贵司存在严重电气火灾安全隐患，为避免造成不可挽救后果，请及时处理！谢谢！
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getSpicalFontColor());
            if(warnType == 1){
//                remark.setValue("温度已超过" + device.getWarnMaxValue() + "℃，请及时处理！");
                remark.setValue("温度已超过预警温度，请及时处理！");
            }else if(warnType == 2){
//                remark.setValue("温度已低于" + device.getWarnMinValue() + "℃，请及时处理！");
                remark.setValue("温度已低于预警温度，请及时处理！");
            }
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    // 判断是否在范围内
    private boolean isInrange(double[] range, double value){
        System.out.println("判断是否在范围内:"+range);
        boolean isInrange = false;
        if (range != null && range.length > 1){
            System.out.println("判断是否在范围内range0:"+range[0] + "range1"+range[1] + "tem0" + value);
            if (value > range[0] && value < range[1]){
                System.out.println("判断是否在范围内:11111111111111111111111");
                return true;
            }
        }
        return isInrange;
    }

    public static void main(String[] args){
        double value = new Double(74.87199);
        double value1 = new Double(70);
        double value3 = new Double(4);
        double[] range = new double[]{value1,value1+value3};
        if (value >= range[0] && value < range[1]){
            System.out.println("判断是否在范围内:11111111111111111111111");
        }else {
            System.out.println("判断是否在范围内:222222222222222");
        }
    }
}
